package com.yupi.yupao.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yupi.yupao.common.BaseResponse;
import com.yupi.yupao.common.DeleteRequest;
import com.yupi.yupao.common.ErrorCode;
import com.yupi.yupao.common.ResultUtils;
import com.yupi.yupao.exception.BusinessException;
import com.yupi.yupao.model.domain.Tag;
import com.yupi.yupao.model.domain.User;
import com.yupi.yupao.model.domain.UserTeam;
import com.yupi.yupao.model.dto.TagQuery;
import com.yupi.yupao.model.request.TagAddRequest;
import com.yupi.yupao.model.request.TagUpdateRequest;
import com.yupi.yupao.model.vo.TagUserVO;
import com.yupi.yupao.model.vo.TeamUserVO;
import com.yupi.yupao.service.TagService;
import com.yupi.yupao.service.UserService;
import com.yupi.yupao.service.UserTagService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author yyzhang
 * @version 1.0
 */
@RestController
@Slf4j
@Api(value = "标签接口")
@RequestMapping("/tag")
public class TagController {
    private final String tagLog="标签接口-";
    @Resource
    private UserService userService;
    @Resource
    private TagService tagService;
    @Resource
    private UserTagService userTagService;
    //标签增删改查和根据列表查询标签
    //增加标签
    @ApiOperation(value = "添加标签")
    @PostMapping("/add")
    public BaseResponse<Long> addTag(@RequestBody TagAddRequest tagAddRequest, HttpServletRequest request) {
        log.info(tagLog+"添加标签-正在调用接口....");
        if(tagAddRequest==null){
            log.error(tagLog+"添加标签-请求参数为空");
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"参数为空");
        }
        User loginUser = userService.getLoginUser(request);
        log.info(tagLog+"添加标签-获取当前登录态");
        if(loginUser==null){
            log.error(tagLog+"添加标签-未登录");
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        if(!userService.isAdmin(loginUser)){
            log.error(tagLog+"添加标签-不是管理员，不可以添加标签");
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        Tag tag = new Tag();
        BeanUtils.copyProperties(tagAddRequest, tag);
        tag.setUserId(loginUser.getId());
        long tagId = tagService.addTag(tag);
        log.info(tagLog+"添加标签-结束接口调用....");
        return ResultUtils.success(tagId);
    }

    @ApiOperation(value = "修改标签")
    @PostMapping("/update")
    public BaseResponse<Boolean> updateTeam(@RequestBody TagUpdateRequest tagUpdateRequest, HttpServletRequest request) {
       log.info(tagLog+"修改标签-开始接口调用.....");
        if (tagUpdateRequest == null) {
            log.error(tagLog+"修改标签-请求参数为空");
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        User loginUser = userService.getLoginUser(request);
        log.info(tagLog+"修改标签-获取当前登录态");
        boolean result = tagService.updateTag(tagUpdateRequest, loginUser);
        if (!result) {
            log.error(tagLog+"修改标签-修改标签失败");
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "更新失败");
        }
        log.info(tagLog+"修改标签-结束接口调用.....");
        return ResultUtils.success(true);
    }

    @ApiOperation(value = "删除标签")
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteTag(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        log.info(tagLog+"删除标签-开始接口调用.....");
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            log.error(tagLog+"删除标签-请求传入的标签id不合法");
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long id = deleteRequest.getId();
        User loginUser = userService.getLoginUser(request);
        log.info(tagLog+"删除标签-获取当前登录态");
        boolean result = tagService.deleteTag(id, loginUser);
        if (!result) {
            log.error(tagLog+"删除标签-将标签表中这个id的行删除失败");
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "删除失败");
        }
        log.info(tagLog+"删除标签-结束接口调用.....");
        return ResultUtils.success(true);
    }

    @ApiOperation(value = "根据id获取标签信息")
    @GetMapping("/get")
    public BaseResponse<Tag> getTagById(long id) {
        log.info(tagLog+"根据id获取标签信息-开始接口调用.....");
        if (id <= 0) {
            log.error(tagLog+"根据id获取标签信息-标签id不合法");
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Tag tag = tagService.getById(id);
        if (tag == null) {
            log.error(tagLog+"根据id获取标签信息-这个标签不存在");
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        log.info(tagLog+"根据id获取标签信息-根据id获取标签对象成功");
        log.info(tagLog+"根据id获取标签信息-结束接口调用.....");
        return ResultUtils.success(tag);
    }

  /*  @GetMapping("/list")
    public BaseResponse<List<TagUserVO>> listTeams(TagQuery tagQuery, HttpServletRequest request) {
        log.info(tagLog+"列表查询标签信息-开始接口调用.....");
        if (tagQuery == null) {
            log.error(tagLog+"列表查询标签信息-查询参数为空");
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean isAdmin = userService.isAdmin(request);
        log.info(tagLog+"列表查询标签信息-查看当前登录用户是否是管理员");
        // 1、查询队伍列表
        List<TagUserVO> tagList = tagService.listTags(tagQuery, isAdmin);
        if(CollectionUtils.isNotEmpty(tagList)) {
            final List<Long> teamIdList = tagList.stream().map(TagUserVO::getId).collect(Collectors.toList());
            // 2、判断当前用户是否已加入队伍
            QueryWrapper<UserTeam> userTeamQueryWrapper = new QueryWrapper<>();
            try {
                User loginUser = userService.getLoginUser(request);
                userTeamQueryWrapper.eq("userId", loginUser.getId());
                userTeamQueryWrapper.in("teamId", teamIdList);
                List<UserTeam> userTeamList = userTagService.list(userTeamQueryWrapper);
                // 已加入的队伍 id 集合
                Set<Long> hasJoinTeamIdSet = userTeamList.stream().map(UserTeam::getTeamId).collect(Collectors.toSet());
                tagList.forEach(team -> {
                    boolean hasJoin = hasJoinTeamIdSet.contains(tag.getId());
                    team.setHasJoin(hasJoin);
                });
            } catch (Exception e) {
            }
            // 3、查询已加入队伍的人数
            QueryWrapper<UserTeam> userTeamJoinQueryWrapper = new QueryWrapper<>();
            userTeamJoinQueryWrapper.in("teamId", teamIdList);
            List<UserTeam> userTeamList = userTagService.list(userTeamJoinQueryWrapper);
            // 队伍 id => 加入这个队伍的用户列表
            Map<Long, List<UserTeam>> teamIdUserTeamList = userTeamList.stream().collect(Collectors.groupingBy(UserTeam::getTeamId));
            tagList.forEach(team -> team.setHasJoinNum(teamIdUserTeamList.getOrDefault(team.getId(), new ArrayList<>()).size()));
        }
        return ResultUtils.success(tagList);
    }
*/
}
